var index;

var table;
var form;
var laydate;

$(document).ready(function () {
    $('#page-toolbar-content').show();

    layui.use(['table', 'form', 'laydate'], function () {

        table = layui.table;
        form = layui.form;
        laydate = layui.laydate;
        form.render();

        getAllButton(currUrl).done(function(returnData) {
            createButton(returnData);
            initButtonEvent();
            initDater();
            initTable();
        });

    });

});

function initButtonEvent() {

    var $ = layui.$, active = {

        add: function () {
            loadingChildPage('/admin/user/user_add', '新增用户');
        },
        edit: function () {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量修改行！");
            }
            else {
                loadingChildPageId('/admin/user/user_edit', '编辑用户', data[0].userId);
            }
        },
        del: function () {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                var dataIds = [];
                for (var i = 0; i < data.length; i++) {
                    dataIds[i] = data[i].userId;
                }

                removeUser(dataIds);
            }
        },
        role: function() {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                var dataIds = [];
                for (var i = 0; i < data.length; i++) {
                    dataIds[i] = data[i].userId;
                }
                var dataIdsJSON = JSON.stringify(dataIds);
                setUserRole(dataIdsJSON);
            }
        },
        search: function () {

            var username = $('#username');
            var nickname = $('#nickname');
            var sex = $('#sex');
            var createTime = $('#createTime');
            var status = $('#status');

            // 执行重载
            table.reload('user-table-content', {
                page: {
                    curr: 1
                }
                , where: {
                    username: username.val(),
                    nickname: nickname.val(),
                    sex: sex.val(),
                    createTime: createTime.val(),
                    status: status.val()
                }
            });

            $('.layui-table-page').css('text-align', 'right');
            $('.layui-table-page').css('padding-right', '20px');

        }
    };

    $('.menu-btn-group .layui-btn, .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

}


function initDater() {
    laydate.render({
        elem: '#createTime'
    });
}


function initTable() {

    table.render({
        elem: '#user-table-content'
        , url: apiHostUrl + '/admin/user/queryUser'
        , headers: {Authorization: token}
        , response: {
            statusName: 'errorCode'
            , statusCode: 0
            , msgName: 'errorMsg'
            , countName: 'totalCount'
            , dataName: 'returnData'
        }
        , cellMinWidth: 50
        , limit: 15
        , limits: [15]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'userId', width: 70, title: 'ID'}
            , {field: 'username', width: 150, title: '用户名'}
            , {field: 'nickname', width: 150, title: '昵称'}
            , {field: 'sexString', width: 60, title: '性别'}
            , {field: 'phone', width: 170, title: '手机号码'}
            , {field: 'email', width: 190, title: '电子邮箱'}
            , {field: 'createTime', width: 170, title: '注册时间'}
            , {field: 'lastLoginTime', width: 170, title: '最后登录时间'}
            , {field: 'lastLoginIp', title: '最后登录IP'}
            , {field: 'statusString', width: 70, title: '状态'}
            , {field: 'toolbar', width: 240, title: '操作', align: 'center', toolbar: '#tableToolbar'}
        ]]
        , page: {
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count']
        }
        , id: 'user-table-content'
    });

    // 监听工具条
    table.on('tool(page-table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            var dataIds = [];
            dataIds[0] = data.userId;
            removeUser(dataIds);
        } else if (obj.event === 'edit') {
            loadingChildPageId('/admin/user/user_edit', '编辑用户', data.userId);
        }
        else if (obj.event === 'role') {
            var dataIds = [];
            dataIds[0] = data.userId;
            var dataIdsJSON = JSON.stringify(dataIds);
            setUserRole(dataIdsJSON);
        }
    });

    $('.layui-table-page').css('text-align', 'right');
    $('.layui-table-page').css('padding-right', '20px');

}

function removeUser(userIds) {
    layer.confirm("真的要删除该行吗？", function () {
        ajax(
            "/admin/user/delUser", "POST",
            {userIds: userIds}
            , true, true, true
        ).done(function () {
            loadingPage("/admin/user/user");
        });
        layer.closeAll();
    });
}

function setUserRole(dataIdsJSON) {

    layui.use('layer', function () {

        var layer = layui.layer;

        index = layer.open({
            title: "设置角色",
            type: 1,
            shade: 0,
            id: 'layer-page-page',
            area: ['330px', '552px'],
            content:
            '<div style="text-align: center;"></div><div id="user-role-tree" style="padding: 20px;min-height: 400px;max-height: 400px;"></div>' +
            '<hr>' +
            '<div class="layui-form-item" style="text-align: center;margin-bottom: 5px;">' +
            '<button class="layui-btn layui-btn-default"><i class="fa fa-check fa-fw"></i>确认</button>' +
            '<button class="layui-btn layui-btn-danger"><i class="fa fa-reply fa-fw"></i>返回</button></div></div>',
            success: function (alertLayer) {
                var btn_ok = alertLayer.find('.layui-btn-default');
                btn_ok.attr({
                    onclick: "javascript:setRole(" + dataIdsJSON + ");"
                });
                var btn_cancel = alertLayer.find('.layui-btn-danger');
                btn_cancel.attr({
                    onclick: 'layer.closeAll();'
                });
            }
        });

        getAllRoleTreeData();
    });
}

function setRole(userIdsJSON) {

    var userIds = JSON.parse("[" + userIdsJSON + "]");

    var tree = $("#user-role-tree");
    var nodes = tree.jstree(true).get_checked(false);

    tree.find(".jstree-undetermined").each(function (i, element) {
        nodes.push($(element).closest('.jstree-node').attr("id"));
    });

    var roleIds = nodes.map(function(data){
        return +data;
    });

    ajax(
        "/admin/user/setRole", "POST",
        {
            userIds: userIds,
            roleIds: roleIds
        }
        , true, true, true
    ).done(function () {
        loadingPage("/admin/user/user");
    });
    layer.closeAll();
}

function getAllRoleTreeData() {

    // 获取所有角色树
    ajax(
        "/admin/role/getRoleTree", "POST",
        null, true, true, false
    ).done(function (returnData) {
        createJSTree(returnData);
    });

}

function createJSTree(jsonData) {

    var tree = $('#user-role-tree');

    tree.jstree({
        plugins: ["state", "checkbox", "types"],
        core: {
            multiple: true,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            default: {
                icon: "fa fa-user icon-state-default icon-lg"
            },
            file: {
                icon: "fa fa-user icon-state-default icon-lg"
            }
        }
    });

    tree.jstree(true).settings.core.data = jsonData;
    tree.jstree(true).refresh();

}


